package com.cetc;

import org.junit.Test;

import java.io.*;

/**
 * @Classname IOBufferStream
 * @Description 缓冲流的使用，其中包括BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
 * @Date 2022/11/24 15:39
 * @Created by louzhuangxi
 */
public class IOBufferStream {

    @Test
    public void test01() {
        File sourceFile = new File("data/1.png");
        File targetFile = new File("data/2.png");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            FileInputStream fis = new FileInputStream(sourceFile);
            FileOutputStream fos = new FileOutputStream(targetFile);
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void test02() {
        File sourceFile = new File("data/hello.txt");
        File targetFile = new File("data/hello3.txt");
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            FileReader fr = new FileReader(sourceFile);
            FileWriter fw = new FileWriter(targetFile);
            br = new BufferedReader(fr);
            bw = new BufferedWriter(fw);
            String data;
            while ((data = br.readLine()) != null){
                bw.write(data);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
